<template>
	<view class="logistics-container page-container">

		<!-- 物流轨迹地图 -->
		<view class="map-section">
			<view class="map-container">
				<map id="logisticsMap" class="logistics-map" :longitude="mapCenter.longitude"
					:latitude="mapCenter.latitude" :scale="mapScale" :markers="mapMarkers" :polyline="mapPolyline"
					:show-location="false" @markertap="onMarkerTap"></map>
				<!-- <view class="map-overlay">
					<view class="current-status">
						<view class="status-icon">
							<u-icon name="car" size="24" color="#ffffff"></u-icon>
						</view>
						<view class="status-info">
							<text class="status-text">{{ logisticsInfo.logistics_status_desc }}</text>
							<text class="status-time">{{ logisticsInfo.last_logistics_time }}</text>
						</view>
					</view>
					<button class="fit-view-btn" @click="fitMapView">
						<u-icon name="scan" size="16" color="#ffffff"></u-icon>
						<text class="fit-text">适应视角</text>
					</button>
				</view> -->
			</view>
			<view class="logistics-company">
				<view class="company-row">
					<text class="company-name">{{ logisticsInfo.lc_name }}</text>
					<button class="refresh-btn" @click="refreshLogistics">
						<text class="refresh-text">刷新</text>
					</button>
				</view>
				<view class="tracking-row">
					<text class="tracking-no">运单号：{{ logisticsInfo.track_no }}</text>
					<button class="copy-btn" @click="copyTrackingNo">复制</button>
				</view>
			</view>
		</view>

		<!-- 物流轨迹 -->
		<view v-if="logisticsInfo.track_info && logisticsInfo.track_info.length>0" class="track-section">
			<view class="section-title">
				<text class="title-text">物流轨迹</text>
			</view>
			<view class="track-list">
				<view class="track-item" v-for="(track, index) in logisticsInfo.track_info" :key="index"
					:class="{ first: index === 0 }">
					<view class="track-dot"></view>
					<view class="track-content">
						<text class="track-desc">{{ track.desc }}</text>
						<text class="track-time">{{ track.time }}</text>
						<text class="track-location" v-if="track.location">{{ track.location }}</text>
					</view>
					<view class="track-line" v-if="index < logisticsInfo.track_info.length - 1"></view>
				</view>
			</view>
		</view>

		<!-- 订单信息 -->
		<view class="order-section">
			<view class="section-title">
				<text class="title-text">订单信息</text>
			</view>
			<view class="order-info">
				<view class="info-item">
					<text class="info-label">订单号</text>
					<text class="info-value">{{ orderInfo.order_no }}</text>
				</view>
				<view class="info-item">
					<text class="info-label">收货人</text>
					<text class="info-value">{{ orderInfo.receiver_name }}</text>
				</view>
				<view class="info-item">
					<text class="info-label">收货地址</text>
					<text class="info-value">{{ orderInfo.pcs + ' ' + orderInfo.receiver_address}}</text>
				</view>
				<view class="info-item">
					<text class="info-label">发货时间</text>
					<text class="info-value">{{ orderInfo.shipTime }}</text>
				</view>
			</view>
		</view>

		<!-- 联系客服 -->
		<view class="contact-section">
			<view class="contact-item" @click="callService">
				<view class="contact-left">
					<u-icon name="phone" size="20" color="#1c705e"></u-icon>
					<text class="contact-text">联系客服</text>
				</view>
				<u-icon name="arrow-right" size="16" color="#999"></u-icon>
			</view>
			<view class="contact-item" @click="callCourier">
				<view class="contact-left">
					<u-icon name="phone" size="20" color="#1c705e"></u-icon>
					<text class="contact-text">联系快递员</text>
				</view>
				<u-icon name="arrow-right" size="16" color="#999"></u-icon>
			</view>
		</view>

		<!-- 温馨提示 -->
		<view class="tips-section">
			<view class="tips-header">
				<u-icon name="info-circle" size="16" color="#999"></u-icon>
				<text class="tips-title">温馨提示</text>
			</view>
			<view class="tips-content">
				<text class="tip-item">• 物流信息可能存在延迟，请以实际配送情况为准</text>
				<text class="tip-item">• 如有疑问，请及时联系客服或快递员</text>
				<text class="tip-item">• 签收前请仔细检查包裹是否完好</text>
			</view>
		</view>
	</view>
</template>

<script>
	import {
		mapGetters
	} from 'vuex'
	export default {
		data() {
			return {
				orderId: '',
				logistics_id: '',
				// 地图相关数据
				mapCenter: {
					longitude: 112.5, // 广西-广东中心经度
					latitude: 23.2 // 广西-广东中心纬度
				},
				mapScale: 5, // 使用更小的缩放级别以显示更大范围
				mapMarkers: [],
				mapPolyline: [],
				logisticsInfo: {
					lc_name: '顺丰速运',
					track_no: 'SF1234567890',
					logistics_status_desc: '运输中',
					last_logistics_time: '2024-07-05 10:30:00',
					track_info: [{
							desc: '快件已到达深圳南山中转场',
							time: '2024-07-05 10:30:00',
							location: '深圳南山中转场',
							longitude: 113.9308,
							latitude: 22.5329
						},
						{
							desc: '快件已从深圳福田中转场发出',
							time: '2024-07-05 08:15:00',
							location: '深圳福田中转场',
							longitude: 114.0579,
							latitude: 22.5431
						},
						{
							desc: '快件已到达深圳福田中转场',
							time: '2024-07-05 06:20:00',
							location: '深圳福田中转场',
							longitude: 114.0579,
							latitude: 22.5431
						},
						{
							desc: '快件已从广州白云中转场发出',
							time: '2024-07-04 22:30:00',
							location: '广州白云中转场',
							longitude: 113.2988,
							latitude: 23.3927
						},
						{
							desc: '快件已到达广州白云中转场',
							time: '2024-07-04 20:15:00',
							location: '广州白云中转场',
							longitude: 113.2988,
							latitude: 23.3927
						},
						{
							desc: '快件已从梧州六堡营业点发出',
							time: '2024-07-04 16:00:00',
							location: '梧州六堡营业点',
							longitude: 111.2792,
							latitude: 23.4748
						},
						{
							desc: '快件已揽收',
							time: '2024-07-04 15:30:00',
							location: '梧州六堡营业点',
							longitude: 111.2792,
							latitude: 23.4748
						}
					]
				},
				orderInfo: {}
			}
		},
		computed: {
			...mapGetters(['dealerInfo'])
		},
		onLoad(options) {
			if (options.orderId && options.logistics_id) {
				this.orderId = options.orderId
				this.logistics_id = options.logistics_id
				this.loadLogisticsInfo()
			}
			this.initMap()
		},
		methods: {
			// 初始化地图
			initMap() {
				this.setupMapMarkers()
				this.setupMapPolyline()
				this.adjustMapView()
			},

			// 调整地图视野
			adjustMapView() {
				if (!(this.logisticsInfo.track_info && this.logisticsInfo.track_info.length > 0)) {
					return
				}
				const tracks = this.logisticsInfo.track_info.filter(track => track.longitude && track.latitude)
				if (tracks.length === 0) return

				// 计算所有点的边界
				let minLng = tracks[0].longitude
				let maxLng = tracks[0].longitude
				let minLat = tracks[0].latitude
				let maxLat = tracks[0].latitude

				tracks.forEach(track => {
					minLng = Math.min(minLng, track.longitude)
					maxLng = Math.max(maxLng, track.longitude)
					minLat = Math.min(minLat, track.latitude)
					maxLat = Math.max(maxLat, track.latitude)
				})

				// 添加边距，确保所有点都在视野内
				const lngPadding = (maxLng - minLng) * 0.2 // 20% 边距
				const latPadding = (maxLat - minLat) * 0.2 // 20% 边距

				minLng -= lngPadding
				maxLng += lngPadding
				minLat -= latPadding
				maxLat += latPadding

				// 设置地图中心点
				this.mapCenter = {
					longitude: (minLng + maxLng) / 2,
					latitude: (minLat + maxLat) / 2
				}

				// 根据跨度调整缩放级别，使用更保守的缩放
				const lngSpan = maxLng - minLng
				const latSpan = maxLat - minLat
				const maxSpan = Math.max(lngSpan, latSpan)

				if (maxSpan > 8) {
					this.mapScale = 4
				} else if (maxSpan > 4) {
					this.mapScale = 5
				} else if (maxSpan > 2) {
					this.mapScale = 6
				} else if (maxSpan > 1) {
					this.mapScale = 7
				} else {
					this.mapScale = 8
				}
			},

			// 设置地图标记点
			setupMapMarkers() {
				if (!(this.logisticsInfo.track_info && this.logisticsInfo.track_info.length > 0)) {
					return
				}
				const markers = []
				// 只在最新位置（第一个轨迹点）添加标记
				const latestTrack = this.logisticsInfo.track_info[0]
				if (latestTrack && latestTrack.longitude && latestTrack.latitude) {
					markers.push({
						id: 0,
						longitude: latestTrack.longitude,
						latitude: latestTrack.latitude,
						title: latestTrack.location,
						width: 40,
						height: 40,
						callout: {
							content: `${latestTrack.location}\n${latestTrack.time}\n${latestTrack.desc}`,
							color: '#333',
							fontSize: 12,
							borderRadius: 4,
							bgColor: '#fff',
							padding: 8,
							display: 'BYCLICK'
						},
						// 当前位置使用红色标记
						label: {
							content: '',
							color: '#fff',
							fontSize: 12,
							borderRadius: 10,
							bgColor: '#ff4757',
							padding: 4
						}
					})
				}

				this.mapMarkers = markers
			},

			// 设置地图路线
			setupMapPolyline() {
				if (!(this.logisticsInfo.track_info && this.logisticsInfo.track_info.length > 0)) {
					return
				}
				const points = []
				// 按时间倒序添加路线点（最新的在前面）
				this.logisticsInfo.track_info.slice().reverse().forEach(track => {
					if (track.longitude && track.latitude) {
						points.push({
							longitude: track.longitude,
							latitude: track.latitude
						})
					}
				})

				if (points.length > 1) {
					this.mapPolyline = [{
						points: points,
						color: '#52a58a',
						width: 4,
						dottedLine: false,
						arrowLine: true
					}]
				}
			},

			// 地图标记点击事件
			onMarkerTap() {
				if (!(this.logisticsInfo.track_info && this.logisticsInfo.track_info.length > 0)) {
					return
				}
				// 点击当前位置标记，显示最新物流信息
				const latestTrack = this.logisticsInfo.track_info[0]
				if (latestTrack) {
					uni.showModal({
						title: '当前位置',
						content: `${latestTrack.location}\n${latestTrack.desc}\n时间：${latestTrack.time}`,
						showCancel: false
					})
				}
			},

			// 适应地图视角
			fitMapView() {
				this.adjustMapView()
				uni.showToast({
					title: '视角已调整',
					icon: 'success',
					duration: 1500
				})
			},

			// 加载物流信息
			loadLogisticsInfo() {
				uni.showLoading({
					title: '加载中...'
				})

				this.$api.order.GetOrdersInfo({
					id: this.orderId
				}).then(res => {
					uni.hideLoading()
					const province = this.$tools.parseJsonObject(res.data.receiver_province)
					const city = this.$tools.parseJsonObject(res.data.receiver_city)
					const town = this.$tools.parseJsonObject(res.data.receiver_town)
					this.orderInfo = res.data;
					if (province && province.name) {
						this.orderInfo.pcs = province.name + city.name + town.name;
					} else {
						this.orderInfo.pcs = ''
					}
					this.orderInfo.receiver_address = this.$secret.decryptAES(this.orderInfo.receiver_address)
					// 物流信息
					this.logisticsInfo = res.data.logistics.find(item => item.id === this.logistics_id)
					if (this.logisticsInfo) {
						// 轨迹节点信息
						this.logisticsInfo.track_info = this.$tools.parseJsonObject(this.logisticsInfo.track_info)
						// 重新初始化地图
						this.initMap()
					}
				})
			},

			// 刷新物流信息
			refreshLogistics() {
				uni.showLoading({
					title: '刷新中...'
				})

				// 模拟刷新API调用延迟
				setTimeout(() => {
					uni.hideLoading()
					uni.showToast({
						title: '刷新成功',
						icon: 'success'
					})
					// 重新加载物流信息
					this.loadLogisticsInfo()
				}, 1500)
			},

			// 复制运单号
			copyTrackingNo() {
				uni.setClipboardData({
					data: this.logisticsInfo.track_no,
					success: () => {
						uni.showToast({
							title: '运单号已复制',
							icon: 'success'
						})
					},
					fail: () => {
						uni.showToast({
							title: '复制失败',
							icon: 'none'
						})
					}
				})
			},

			// 联系客服
			callService() {
				if (this.dealerInfo.shop_tel && this.dealerInfo.shop_tel != '') {
					uni.makePhoneCall({
						phoneNumber: this.dealerInfo.shop_tel
					})
				} else {
					uni.showToast({
						title: '暂未设置客服电话',
						icon: 'none'
					})
				}
			},

			// 联系快递员
			callCourier() {
				uni.showModal({
					title: '联系快递员',
					content: '快递员电话：138****8888',
					confirmText: '拨打',
					success: (res) => {
						if (res.confirm) {
							uni.makePhoneCall({
								phoneNumber: '13888888888',
								success: () => {
									// console.log('拨打快递员电话成功')
								},
								fail: (err) => {
									// console.log('拨打快递员电话失败', err)
									uni.showToast({
										title: '拨打失败',
										icon: 'none'
									})
								}
							})
						}
					}
				})
			}
		}
	}
</script>

<style lang="scss" scoped>
	.logistics-container {
		background-color: #f8f8f8;
		min-height: 100vh;
	}

	.map-section {
		margin: 20rpx;
		border-radius: 16rpx;
		overflow: hidden;
		box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.08);
	}

	.map-container {
		position: relative;
		height: 400rpx;
	}

	.logistics-map {
		width: 100%;
		height: 100%;
	}

	.map-overlay {
		position: absolute;
		top: 20rpx;
		left: 20rpx;
		right: 20rpx;
		z-index: 10;
		display: flex;
		justify-content: space-between;
		align-items: flex-start;
	}

	.current-status {
		background-color: rgba(82, 165, 138, 0.9);
		border-radius: 12rpx;
		padding: 20rpx;
		display: flex;
		align-items: center;
		backdrop-filter: blur(10rpx);
		flex: 1;
		margin-right: 16rpx;
	}

	.fit-view-btn {
		background-color: rgba(82, 165, 138, 0.9);
		border: none;
		border-radius: 12rpx;
		padding: 20rpx;
		display: flex;
		align-items: center;
		backdrop-filter: blur(10rpx);
		min-width: 120rpx;
		justify-content: center;
	}

	.fit-text {
		font-size: 24rpx;
		color: #ffffff;
		margin-left: 8rpx;
	}

	.status-icon {
		margin-right: 20rpx;
	}

	.status-info {
		flex: 1;
	}

	.status-text {
		font-size: 28rpx;
		font-weight: bold;
		color: #ffffff;
		margin-bottom: 6rpx;
		display: block;
	}

	.status-time {
		font-size: 24rpx;
		color: rgba(255, 255, 255, 0.9);
		display: block;
	}

	.logistics-company {
		padding: 20rpx;
		background-color: #f9f9f9;
		border-radius: 12rpx;
	}

	.company-row {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 12rpx;
	}

	.company-name {
		font-size: 28rpx;
		color: #333;
	}

	.refresh-btn {
		display: flex;
		align-items: center;
		background-color: transparent;
		border: 1rpx solid #1c705e;
		border-radius: 8rpx;
		padding: 0rpx 12rpx;
		font-size: 22rpx;
	}

	.refresh-text {
		font-size: 22rpx;
		color: #1c705e;
		margin-left: 6rpx;
	}

	.tracking-row {
		display: flex;
		justify-content: space-between;
		align-items: center;
	}

	.tracking-no {
		font-size: 24rpx;
		color: #666;
	}

	.copy-btn {
		background-color: #1c705e;
		color: #ffffff;
		border: none;
		border-radius: 8rpx;
		padding: 0rpx 16rpx;
		font-size: 22rpx;
	}

	.track-section,
	.order-section,
	.contact-section,
	.tips-section {
		background-color: #ffffff;
		margin: 20rpx;
		border-radius: 16rpx;
		padding: 40rpx;
	}

	.section-title {
		margin-bottom: 30rpx;
	}

	.title-text {
		font-size: 32rpx;
		font-weight: bold;
		color: #333;
	}

	.track-list {
		position: relative;
		margin-top: 20rpx;
	}

	.track-item {
		position: relative;
		display: flex;
		margin-bottom: 40rpx;
	}

	.track-item:last-child {
		margin-bottom: 0;
	}

	.track-dot {
		width: 20rpx;
		height: 20rpx;
		background-color: #e5e5e5;
		border-radius: 50%;
		margin-right: 30rpx;
		margin-top: 8rpx;
		flex-shrink: 0;
	}

	.track-item.first .track-dot {
		background-color: #1c705e;
	}

	.track-content {
		flex: 1;
	}

	.track-desc {
		font-size: 28rpx;
		color: #333;
		margin-bottom: 8rpx;
		display: block;
	}

	.track-time {
		font-size: 24rpx;
		color: #666;
		margin-bottom: 8rpx;
		display: block;
	}

	.track-location {
		font-size: 22rpx;
		color: #999;
		display: block;
	}

	.track-line {
		position: absolute;
		left: 10rpx;
		top: 28rpx;
		width: 2rpx;
		height: 40rpx;
		background-color: #e5e5e5;
	}

	.order-info {
		margin-top: 20rpx;
	}

	.info-item {
		display: flex;
		justify-content: space-between;
		align-items: flex-start;
		margin-bottom: 20rpx;
	}

	.info-item:last-child {
		margin-bottom: 0;
	}

	.info-label {
		font-size: 26rpx;
		color: #666;
		width: 160rpx;
		flex-shrink: 0;
	}

	.info-value {
		font-size: 26rpx;
		color: #333;
		flex: 1;
		text-align: right;
		line-height: 1.5;
	}

	.contact-item {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 30rpx 0;
		border-bottom: 2rpx solid #f5f5f5;
	}

	.contact-item:last-child {
		border-bottom: none;
	}

	.contact-left {
		display: flex;
		align-items: center;
	}

	.contact-text {
		font-size: 28rpx;
		color: #333;
		margin-left: 16rpx;
	}

	.tips-header {
		display: flex;
		align-items: center;
		margin-bottom: 20rpx;
	}

	.tips-title {
		font-size: 28rpx;
		color: #666;
		margin-left: 12rpx;
	}

	.tips-content {
		padding-left: 28rpx;
	}

	.tip-item {
		font-size: 24rpx;
		color: #999;
		line-height: 1.6;
		margin-bottom: 8rpx;
		display: block;
	}

	.tip-item:last-child {
		margin-bottom: 0;
	}
</style>